<template>
  <transition>
    <div class="app-upload-photos">
      <section>
        <ul class="module-photo">
          <!--{{mediaAttr}}-->
          <!--{{accessToken}}-->

          <li class="item">
            <span class="addon">车辆/定损照：</span>
            <dl class="img-upload-content me-row">
              <dd class="item me-col-3" v-for="(item,index) in files" v-if="item.fileLocate=='车辆图片'">
                <span class="iconfont icon-shanchu" @click="handleDelImg(index,item)"></span>
                <img class="img" :src="item.src" @click="handleCheckPic(index)"/>
              </dd>
              <dd class="item me-col-3 item-add ">
                <span class="input-upload" @click="handleSelectImg('车辆图片')"></span>
                <span class="iconfont add-img icon-xiangjizhuanhuan">添加图片</span>
              </dd>
            </dl>
          </li>
          <li class="item">
            <span class="addon">证件照：</span>
            <dl class="img-upload-content me-row">
              <dd class="item me-col-3" v-for="(item,index) in files"v-if="item.fileLocate=='证件照'">
                <span class="iconfont icon-shanchu" @click="handleDelImg(index,item)"></span>
                <img class="img" :src="item.src" @click="handleCheckPic(index)"/>
              </dd>
              <dd class="item me-col-3 item-add">
                <span class="input-upload" @click="handleSelectImg('证件照')"></span>
                <span class="iconfont add-img icon-xiangjizhuanhuan">添加图片</span>
              </dd>
            </dl>
          </li>
          <li class="item">
            <span class="addon">复勘验标：</span>
            <dl class="img-upload-content me-row">
              <dd class="item me-col-3" v-for="(item,index) in files" v-if="item.fileLocate=='复勘验标'">
                <span class="iconfont icon-shanchu" @click="handleDelImg(index,item)"></span>
                <img class="img" :src="item.src" @click="handleCheckPic(index)"/>
              </dd>
              <dd class="item me-col-3 item-add ">
                <span class="input-upload" @click="handleSelectImg('复勘验标')"></span>
                <span class="iconfont add-img icon-xiangjizhuanhuan">添加图片</span>
              </dd>
            </dl>
          </li>
        </ul>
        <div class="add-other-info">
          <span class="info-header">【 请注意搞好卫生，贴回原车标贴 】</span>
          <div class="info-list">
            <div class="info-list-header">是否签单</div>
            <mt-radio
              title=""
              v-model="post.isWritten"
              :options="optionsSituationFirst">
            </mt-radio>
          </div>

          <div class="info-list">
            <div class="info-list-header">是否收款</div>
            <mt-radio
              title=""
              v-model="post.isGathering"
              :options="optionsSituationSecond">
            </mt-radio>
          </div>

        </div>

        <div class="button-content">
          <div class="button-block-6">
            <mt-button type="default" @click="handleBack">返回</mt-button>
          </div>
          <div class="button-block-6">
            <mt-button type="danger" @click="handleTest">确认提交</mt-button>
          </div>
        </div>

      </section>

      <mt-popup
        v-model="popupSwiper"
        position="middle" class="me-popup me-popup-pic"  @click.native="handleCloseSwiper">
        <!--<span class="iconfont icon-close2 icon-close-pic" @click="popupSwiper=false"></span>-->
        <mt-swipe :auto="0" v-if="picList.length>0" class="swiper-pic" :defaultIndex="picIndex">
          <mt-swipe-item v-for="(item,index) in picList">
            <div class="item-content">
              <img class="img" :src="item.src"/>
            </div>
            <span class="item-title">{{index+1}}/{{picList.length}}　{{item.fileLocate}}</span>
          </mt-swipe-item>
        </mt-swipe>
        <div class="pic-none" v-if="picList.length<=0">
          暂无图片信息
        </div>
      </mt-popup>

    </div>
  </transition>
</template>

<script>
  import {Button,Toast,Indicator,Radio} from 'mint-ui';

  //  Vue.component(Header.name, Header);
  export default {
    data () {
      return {
        res:'',
        files:[],
        picList:[],
        picIndex:0,
        popupSwiper:false,
        selectSituationFirst:'',
        optionsSituationFirst:[
          {
            label:'已签单',
            value:'1',
          },{
            label:'未签单',
            value:'0',
          },{
            label:'免签单',
            value:'2',
          },
        ],
        selectSituationSecond:'',
        optionsSituationSecond:[{
          label:'已收款',
          value:'1',
        },{
          label:'未收款',
          value:'0',
        },
        ],
        mediaAttr:[],
        post:{
          isWritten:'',
          isGathering:'',
          uploads:[],
        },
        myUploads:[],
        url:'',
        wxConfig:'',
        accessToken:'',
        textAttr:[],
      }
    },
    beforeRouteEnter (to, from, next) {
      var u = navigator.userAgent;
      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      // XXX: 修复iOS版微信HTML5 History兼容性问题
      if (isiOS && to.path !== location.pathname) {
        // 此处不可使用location.replace
        location.assign(to.fullPath)
      } else {
        next()
      }
    },
    mounted(){

      this.getOss();
      this.getData();
//     this.mediaAttr=[{ "serverId": "Zqq1DzFPfLWKs5j0waaFxrq8zrisFkPs434C204ZZaL-DqfIUgiy1mwzO_ECAmwM", "tag": "", "fileLocate": "车辆图片" }, { "serverId": "mXpNNL29Ghsdu6nQe9rvNF8pakDRWBkO84KO6Nkpq3Tw1NhAdgiOhW5A5Iroci_r", "tag": "", "fileLocate": "证件照" } ]
      //  调取微信配置接口
      this.url=location.href;
      var params = new URLSearchParams();
      params.append('url',this.url);
      this.$axios({
        method: 'post',
        url:'gp/bu/wechat!getJsapi.do',
        data:params
      }).then((res)=> {
        this.wxConfig=res.data.object;

      this.accessToken=res.data.object.accessToken;
      this.$wx.config({
        beta: true,// 必须这么写，否则wx.invoke调用形式的jsapi会有问题
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: this.wxConfig.appid, // 必填，企业微信的corpID
        timestamp:this.wxConfig.timestamp, // 必填，生成签名的时间戳
        nonceStr: this.wxConfig.nonceStr, // 必填，生成签名的随机串
        signature: this.wxConfig.signature,// 必填，签名，见附录1
        jsApiList: ['chooseImage','uploadImage','getLocalImgData','downloadImage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
      });
    });
    },
    watch:{},
    methods:{
      getData(){
        this.mediaAttr=[];
        this.files=[];
        this.picList=[];
        this.post.uploads=[];
        this.myUploads=[];
        var params = new URLSearchParams();
        params.append('form.demandId',this.$route.query.id);
        params.append('businessType',1);
        this.$axios({
          method: 'post',
          url:'gp/bu/serviceDemandApp!demandDetail.do',
          data:params
        }).then((res)=>{
          console.log(res)
        if(res.data.result==true){
        this.res=res.data.object;
          this.post.uploads=this.res.uploads;
          if(this.res.isWritten!==undefined){
            this.post.isWritten=this.res.isWritten.toString();
          }
          if(this.res.isGathering!==undefined){
            this.post.isGathering=this.res.isGathering.toString();
          }
          console.log(this.post.uploads)
          for(var i=0;i<this.post.uploads.length;i++){

            if(this.post.uploads[i].fileType==1){
              const item = {
                id:this.post.uploads[i].uploadId,
                name: this.post.uploads[i].sourceFileName,
                tag : this.post.uploads[i].etag,
                fileLocate:this.post.uploads[i].fileLocate,
                src: 'https://rmcbapp.oss-cn-shenzhen.aliyuncs.com/'+this.post.uploads[i].ossPath+'?x-oss-process=image/resize,m_fixed,w_500',
                serverId:'',
              }
              this.files.push(item);
              this.mediaAttr.push(item);

              this.myUploads.push(item);
            }
          }
        }
      });
      },
      //  删除图片
      handleDelImg(index,item){
        this.files.splice(index, 1);
        this.mediaAttr.splice(index, 1);
        console.log(item)
        if(item.id!==undefined){
          var params = new URLSearchParams();
          params.append('form.uploadId',item.id);
          params.append('form.businessId',this.$route.query.id);
          this.$axios({
            method: 'post',
//            url:'gp/bu/serviceDemandApp!uploadDel.do',
            url:'gp/bu/ossUpload!deleteOssUpload.do',
            data:params
          }).then((res)=>{
            if(res.data.result==true){
            Toast({
              message: res.data.message,
              position: 'middle',
              duration:600
            });
//            this.getData();
          }
        });
        }
      },
      handleBack(){
        this.$router.push({path:'/push-order-details',query: {id:this.$route.query.id}})
      },
      /** 查看图片 **/
      handleCheckPic(idx){
        this.picIndex=idx
        this.picList=[];
        for(var i=0;i<this.files.length;i++){
          const picItem = {
            src: this.files[i].src,
            fileLocate:this.files[i].fileLocate
          }
          this.picList.push(picItem)
        }
        this.popupSwiper=true;
      },
      handleSelectImg(fileLocate){
        this.$wx.ready(()=>{
          var u = navigator.userAgent;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

        var _this=this;
        var syncUpload = function(localIds){
          var localId = localIds.pop();
          _this.$wx.uploadImage({
            localId: localId.toString(), // 需要上传的图片的本地ID，由chooseImage接口获得
            isShowProgressTips:1, // 默认为1，显示进度提示
            success: function (res) {
              //res.serverId 返回图片的服务器端ID
              var serverId = res.serverId; // 返回图片的服务器端ID
              const item={
                serverId:res.serverId,
                tag : '',
                fileLocate:fileLocate,
              }
              _this.mediaAttr.push(item);
              if(localIds.length > 0){
                window.setTimeout(function(){
                  syncUpload(localIds);
                },100);
              }else{
                window.setTimeout(function(){
                  downloadImage(0);
                },100);

              }
            }
          })
        }
        _this.$wx.chooseImage({
          count: 9, // 默认9
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          defaultCameraMode: "batch", //表示进入拍照界面的默认模式，目前有normal与batch两种选择，normal表示普通单拍模式，batch表示连拍模式，不传该参数则为normal模式。（注：用户进入拍照界面仍然可自由切换两种模式）
          success: function (res) {

            var localIds = res.localIds; // 返回选定照片的本地ID列表，

            for(var i=0;i<localIds.length;i++){
              if(isiOS==true){

                _this.$wx.getLocalImgData({
                  localId: localIds[i], // 图片的localID
                  success: function (res) {
                    var localData = res.localData; // localData是图片的base64数据，可以用img标签显示
                    const item={
                      src:localData,
                      tag : '',
                      fileLocate:fileLocate,
                    };
                    _this.files.push(item);
                    console.log(_this.files);

                  },
                  fail: function(res) {
                    console.log(res)
                  }
                });
              }else{
                const item={
                  src:localIds[i],
                  tag : '',
                  fileLocate:fileLocate,
                };
                _this.files.push(item);
              }


            }

            syncUpload(res.localIds)
            // andriod中localId可以作为img标签的src属性显示图片；
            // 而在IOS中需通过上面的接口getLocalImgData获取图片base64数据，从而用于img标签的显示
          }
        });
      })
      },
      /**获取oss配置**/
      getOss(){
        let OSS = require('ali-oss');
        this.client = new OSS({
          region: "oss-cn-shenzhen",
          secure: true,//https
          endpoint: 'oss-cn-shenzhen.aliyuncs.com',
          accessKeyId: "LTAIPCNdQvX5yOwc",
          accessKeySecret: "7bReGAz8bc9aJdK4IAz5KW5fnNOzrQ ",
          bucket: 'rmcbapp'
        });
      },
      toBuffer(ab) {
        var buf = new Buffer(ab.byteLength);
        var view = new Uint8Array(ab);
        for (var i = 0; i < buf.length; ++i) {
          buf[i] = view[i];
        }
        return buf;
      },
      handleTest(){

        var params = new URLSearchParams();
        this.post.id=this.$route.query.id;
        params.append('id',this.$route.query.id);
        params.append('demandData',JSON.stringify(this.post));
        this.$axios({
          method: 'post',
          url:'gp/bu/serviceDemandApp!uploadRecord.do',
          data:params
        }).then((res)=>{
          console.log(435345345);
          if(res.data.result==true){
          Toast({
            message: '提交成功',
            position: 'middle',
            duration:500
          });
        }
      });

        this.getOss();
        var that=this;
        for(var i=0;i<that.mediaAttr.length;i++){

          const mediaId = that.mediaAttr[i].serverId; // 微信多媒体文件id
          const fileLocate = that.mediaAttr[i].fileLocate; // 微信多媒体文件id
          const tag = that.mediaAttr[i].tag; // 微信多媒体文件id

          if(tag==''){
            Indicator.open({
              text: '图片上传中...',
              spinnerType: 'snake'
            });
            that.$axios({
              method: 'get',
              url:'wx/cgi-bin/media/get?access_token='+that.accessToken+'&media_id='+mediaId,
              responseType:'arraybuffer',
            }).then((res)=>{
              // arrayBuffer转Buffer

              var buffer = that.toBuffer(res.data);
            var destPath = 'erpService/'+that.$route.query.id+'/'+fileLocate+'/'+mediaId+'.jpg'; // OSS文件路径
            console.log(buffer)
            var postitem={}
            that.client.put(destPath, buffer).then((result) => {
              console.log('图片上传阿里云结果', result);
//        results.res.headers.etag
            postitem={
              bucketName:'rmcbapp',
              fileLocate:result.name.split('/')[2],
              fileType:1,
              sourceFileName:mediaId+'.jpg',
              ossPath:result.name,
              ossKey:'rmcbapp/'+result.name,
              etag:result.res.headers.etag
            }
            that.post.uploads.push(postitem);
            that.myUploads.push(postitem);
            console.log(that.post.uploads)
            if(that.myUploads.length==i){
              that.post.id=that.$route.query.id;
              that.post.uploadFlag=1;
              var params = new URLSearchParams();
              params.append('uploadFlag',1);
              params.append('id',that.$route.query.id);
              params.append('demandData',JSON.stringify(that.post));
              that.$axios({
                method: 'post',
                url:'gp/bu/serviceDemandApp!uploadRecord.do',
                data:params
              }).then((res)=>{
                if(res.data.result==true){
                console.log(res,11111)
                Indicator.close();
                Toast({
                  message: '上传成功',
                  position: 'middle',
                  duration:500
                });
                that.$router.push({path:'/push-order-details',query: {id:that.$route.query.id}})
              }else{
                Indicator.close();
                Toast({
                  message: res.data.message,
                  position: 'middle',
                  duration:500
                });
              }
            }).catch((error)=> {
                Indicator.close();
              Toast({
                message: error,
                position: 'middle',
                duration:20000
              });
            });
            }

          }).catch((err) => {
              console.log(err)
            Indicator.close();
            Toast({
              message: '上传失败1111',
              position: 'middle',
              duration:500
            });
          });

          })
          }else{
            console.log('该图片已上传')
          }
        };
      },
      /** 关闭图片轮转弹窗**/
      handleCloseSwiper(){
        this.popupSwiper=false;
        setTimeout(()=>{
          this.picList=[];
      },500)

      },
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style>

  .add-img{
    display: block;
    padding:22px 0 0;
    height: 100px;
    text-align: center;
    color: #888;
  }
  .add-img:before{
    display: block;
    margin:0 auto 4px;
    font-size:24px;
  }

  .app-upload-photos{
    background: #fff;
  }
  .app-upload-photos .img-upload-content .item-add{
    border:1px dashed #ddd;
  }
  .mint-indicator-wrapper{
    z-index:1000001;
  }
  .app-upload-photos .module-photo{
    padding:16px 0 0;
  }
  .app-upload-photos .module-photo .addon{
    padding:0 12px ;
    font-size: 16px;
    color: #666;
  }
  .app-upload-photos .img-upload-content{
    padding:14px 12px 0;
    margin: 0;
  }
  .app-upload-photos .img-upload-content .item{
    position: relative;
    height: 100px;
    padding:0 12px 0 0;
    margin:0 0 20px;
  }
  .app-upload-photos .img-upload-content img{
    width: 100%;
    height: 100px;
  }
  .app-upload-photos .img-upload-content .icon-shanchu{
    background:rgba(225,225,225,0.5) !important;
    position: absolute;
    top:0;
    right:12px;
    width: 24px;
    height: 24px;
    font-size:18px !important;
    color:#fff;
    text-align: center;
    line-height: 28px;
  }
  .app-upload-photos .img-upload-content .item-add .icon-jiahao{
    display: block;
    height: 100px;
    font-size: 50px;
    color: #ddd;
    line-height: 100px;
    text-align: center;
    border:1px dashed #ddd;
  }
  .app-upload-photos .input-upload {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 4;
    opacity: 0;
    font-size: 0;
    width: 100%;
  }

  .app-upload-photos .button-content{
    padding:24px ;
    text-align: center;
  }
  .app-upload-photos .button-content .mint-button{
    font-size: 16px;
  }
  .app-upload-photos .button-block-6{
    display: inline-block;
    width:46%;
    padding:0 8px;
  }
  .app-upload-photos .button-content .mint-button--default{
    background-color:#fff;
  }
  .app-upload-photos .button-content .mint-button{
    width: 100%;
    font-size: 16px;
  }

  .app-upload-photos .pic-none{
    font-size: 18px;
    color: #999;
    text-align: center;
  }
  .app-upload-photos .mint-swipe{
    background: #000;
    text-align: center;
  }
  .app-upload-photos .swiper-pic .item-content{
    position: absolute;
    left: 0;
    right: 0;
    top:0;
    bottom: 0;
  }
  .app-upload-photos .swiper-pic .item-title{
    background:rgba(0,0,0,0.5);
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    padding:12px 0;
    font-size: 16px;
    color: #fff;
  }
  .app-upload-photos .swiper-pic .mint-swipe-indicators{
    display: none;
  }
  .app-upload-photos .mint-swipe img{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    display: block;
    max-width: 100%;
    max-height:100%;
  }
  .app-upload-photos .me-popup-pic{
    width: 100%;
    height:100%;
  }
  .app-upload-photos .icon-close-pic{
    background: #c34853;
    position: absolute;
    top:0;
    right:0;
    z-index:2000;
    width: 48px;
    height: 48px;
    font-size: 24px;
    color:#fff;
    text-align: center;
    line-height: 48px;
  }

  .me-popup-pic .mint-swipe,.me-popup-pic .mint-swipe-items-wrap{
    height: 100% !important;
  }
  .me-col-3{
    width:33.2% !important;
  }
  .add-other-info .info-header{
    margin:0 0 14px;
    font-size:18px;
    display: block;
    color:#3e3c3c;
    font-weight: bold;
    padding:6px 10px 14px;
    border-bottom: 1px solid #ddd;
    text-align: center;
  }
  .info-list{
    padding:0 10px;
  }
  .info-list .mint-cell{
    display:inline-block;
    width: 46%;
  }

  .app-upload-photos .info-list-header{
    position: relative;
    display: block;
    padding:4px 12px 0;
    font-size:15px;
    color: #666;
  }
  .app-upload-photos .info-list-header:before{
    background:#c34853;
    position: relative;
    top:-2px;
    display:inline-block;
    vertical-align: middle;
    width:2px;
    height:16px;
    content: '';
    margin-right:5px;
  }
  .info-list .mint-cell .mint-cell-wrapper{
    background:none;
    /*padding: 0;*/
  }
  .info-list .mint-radiolist .mint-cell:last-child{
    background:none !important;
  }
  .module-photo-tips{
    padding:0 12px 12px 0;
    text-align: right;
    font-size: 15px;
    color: #999;
  }
</style>
